package org.enhance.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * @author JiangGengchao
 * @classname ExceptionUtil
 * @description 工具
 * @date 2020-03-28
 **/
@Slf4j
public class ExceptionUtil {
	private ExceptionUtil() {
		throw new IllegalStateException("Constant class");
	}

	public static String toMessage(Throwable throwable) {
		return toMessage(throwable, false);
	}

	public static String toMessage(Throwable throwable, boolean showStackTrace) {
		return toMessage(throwable, 4000, showStackTrace);
	}

	public static String toMessage(Throwable throwable, int maxLength, boolean showStackTrace) {
		String message = null;
		if (null != throwable) {
			message = throwable.getMessage();
			if (StringUtils.isEmpty(message) || showStackTrace) {
				message = toDetailErrorMessage(throwable);
			}
			if (message.length() > maxLength) {
				message = message.substring(0, maxLength - 1);
			}
		}
		return message;
	}

	private static String toDetailErrorMessage(Throwable throwable) {
		if (null != throwable) {
			try (StringWriter writer = new StringWriter();) {
				write(throwable, writer);
				return writer.toString();
			} catch (IOException e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;
	}

	private static void write(Throwable throwable, StringWriter writer) {
		if (null != throwable) {
			PrintWriter printWriter = new PrintWriter(writer);
			throwable.printStackTrace(printWriter);
			printWriter.close();
			printWriter = null;
		}
	}

}